package influx

import (
	"context"
	"judge-service/configs"
	"judge-service/proto/report"
	"log"
	"time"

	influxdb2 "github.com/influxdata/influxdb-client-go/v2"
	"github.com/pkg/errors"
)

func WriteReport(ctx context.Context, req *report.ReportReq) error {
	client := influxdb2.NewClient(configs.GetConfig().InfluxUrl,
		configs.GetConfig().Token)
	defer client.Close()
	writeAPI := client.WriteAPIBlocking(configs.GetConfig().Org,
		configs.GetConfig().Bucket)

	// 定义数据点
	point := influxdb2.NewPoint(req.GetMetric(),
		req.GetDimensions(),
		map[string]interface{}{"value": req.GetValue()},
		time.Unix(req.GetTimestamp(), 0))

	// 写入数据点
	err := writeAPI.WritePoint(ctx, point)
	if err != nil {
		log.Printf("%v", err)
		return errors.New("fail to write a point")
	}
	log.Printf("write a point: %+v", req)
	return nil
}

// aiWZX19951206
